<template>
  <div class="detail-report-table">
    <el-tabs
      v-model="activeTab"
      class="report-tabs"
      @tab-change="handleTabChange"
    >
      <el-tab-pane label="资产报表" name="asset" />
      <el-tab-pane label="任务报表" name="task" />
      <el-tab-pane label="风险报表" name="risk" />
      <el-tab-pane label="部门报表" name="department" />
      <el-tab-pane label="责任人报表" name="person" />
    </el-tabs>

    <div class="table-content">
      <DynamicTable
        :data="tableData"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        border
        row-key="id"
        @size-change="handleSizeChange"
        @current-page-change="handlePageChange"
      >
        <!-- 风险等级插槽 -->
        <template #risk_level="{ row }">
          <el-tag
            v-if="row.risk_level"
            :type="getRiskLevelType(row.risk_level)"
            size="small"
          >
            {{ getRiskLevelLabel(row.risk_level) }}
          </el-tag>
          <span v-else class="no-data">-</span>
        </template>

        <!-- 状态插槽 -->
        <template #status="{ row }">
          <el-tag
            v-if="row.status"
            :type="getStatusType(row.status)"
            size="small"
          >
            {{ row.status_name || row.status }}
          </el-tag>
          <span v-else class="no-data">-</span>
        </template>

        <!-- 处理状态插槽 -->
        <template #processing_status="{ row }">
          <el-tag
            v-if="row.processing_status"
            :type="getProcessingStatusType(row.processing_status)"
            size="small"
          >
            {{ row.processing_status_name || row.processing_status }}
          </el-tag>
          <span v-else class="no-data">-</span>
        </template>
      </DynamicTable>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import { getDetailReport } from "../../../servers";
import { ElMessage } from "element-plus";
import { riskLevelList } from "../../../helps";

const props = defineProps<{
  timeRange?: string;
  dateRange?: [Date, Date] | null;
}>();

const emit = defineEmits<{
  (e: "tab-change", tab: string): void;
}>();

const activeTab = ref("asset");
const loading = ref(false);
const tableData = ref<any[]>([]);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 格式化日期
const formatDate = (date: Date) => {
  return `${date.getFullYear()}-${(date.getMonth() + 1)
    .toString()
    .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
};

// 资产报表列配置
const assetColumns: TableColumn[] = [
  {
    label: "资产ID",
    prop: "asset_id",
    minWidth: 120,
    align: "center",
  },
  {
    label: "资产IP",
    prop: "asset_ip",
    minWidth: 140,
  },
  {
    label: "端口",
    prop: "asset_port",
    minWidth: 80,
    align: "center",
  },
  {
    label: "服务类型",
    prop: "service_type",
    minWidth: 100,
    align: "center",
  },
  {
    label: "资产标题",
    prop: "asset_title",
    minWidth: 200,
    showOverflowTooltip: true,
  },
  {
    label: "风险等级",
    prop: "risk_level",
    minWidth: 100,
    align: "center",
    slot: "risk_level",
  },
  {
    label: "所属部门",
    prop: "department_name",
    minWidth: 120,
  },
  {
    label: "责任人",
    prop: "responsible_person",
    minWidth: 100,
  },
  {
    label: "首次检测",
    prop: "first_detected",
    minWidth: 160,
  },
  {
    label: "最后检测",
    prop: "last_detected",
    minWidth: 160,
  },
];

// 任务报表列配置
const taskColumns: TableColumn[] = [
  {
    label: "任务ID",
    prop: "task_id",
    minWidth: 120,
    align: "center",
  },
  {
    label: "任务名称",
    prop: "task_name",
    minWidth: 200,
    showOverflowTooltip: true,
  },
  {
    label: "任务类型",
    prop: "task_type",
    minWidth: 100,
    align: "center",
  },
  {
    label: "执行状态",
    prop: "status",
    minWidth: 100,
    align: "center",
    slot: "status",
  },
  {
    label: "执行次数",
    prop: "execution_count",
    minWidth: 100,
    align: "right",
  },
  {
    label: "成功次数",
    prop: "success_count",
    minWidth: 100,
    align: "right",
  },
  {
    label: "失败次数",
    prop: "failed_count",
    minWidth: 100,
    align: "right",
  },
  {
    label: "成功率",
    prop: "success_rate",
    minWidth: 100,
    align: "right",
    formatter: (row: any) => {
      return row.success_rate ? `${row.success_rate}%` : "-";
    },
  },
  {
    label: "检测资产数",
    prop: "assets_detected",
    minWidth: 120,
    align: "right",
  },
  {
    label: "创建时间",
    prop: "created_time",
    minWidth: 160,
  },
  {
    label: "最后执行",
    prop: "last_execution",
    minWidth: 160,
  },
];

// 风险报表列配置
const riskColumns: TableColumn[] = [
  {
    label: "风险ID",
    prop: "risk_id",
    minWidth: 120,
    align: "center",
  },
  {
    label: "资产IP",
    prop: "asset_ip",
    minWidth: 140,
  },
  {
    label: "端口",
    prop: "asset_port",
    minWidth: 80,
    align: "center",
  },
  {
    label: "风险等级",
    prop: "risk_level",
    minWidth: 100,
    align: "center",
    slot: "risk_level",
  },
  {
    label: "风险分数",
    prop: "risk_score",
    minWidth: 100,
    align: "right",
  },
  {
    label: "风险类型",
    prop: "risk_type",
    minWidth: 120,
  },
  {
    label: "风险描述",
    prop: "risk_description",
    minWidth: 200,
    showOverflowTooltip: true,
  },
  {
    label: "处理状态",
    prop: "processing_status",
    minWidth: 100,
    align: "center",
    slot: "processing_status",
  },
  {
    label: "所属部门",
    prop: "department_name",
    minWidth: 120,
  },
  {
    label: "发现时间",
    prop: "detected_time",
    minWidth: 160,
  },
];

// 部门报表列配置
const departmentColumns: TableColumn[] = [
  {
    label: "部门名称",
    prop: "department_name",
    minWidth: 150,
  },
  {
    label: "总资产",
    prop: "total_assets",
    minWidth: 100,
    align: "right",
  },
  {
    label: "新增资产",
    prop: "new_assets",
    minWidth: 100,
    align: "right",
  },
  {
    label: "高风险资产",
    prop: "high_risk_assets",
    minWidth: 120,
    align: "right",
  },
  {
    label: "中风险资产",
    prop: "medium_risk_assets",
    minWidth: 120,
    align: "right",
  },
  {
    label: "低风险资产",
    prop: "low_risk_assets",
    minWidth: 120,
    align: "right",
  },
  {
    label: "处理率",
    prop: "processing_rate",
    minWidth: 100,
    align: "right",
    formatter: (row: any) => {
      return row.processing_rate ? `${row.processing_rate}%` : "-";
    },
  },
  {
    label: "平均处理时间",
    prop: "avg_processing_time",
    minWidth: 120,
    align: "right",
    formatter: (row: any) => {
      return row.avg_processing_time ? `${row.avg_processing_time}天` : "-";
    },
  },
  {
    label: "准时率",
    prop: "on_time_rate",
    minWidth: 100,
    align: "right",
    formatter: (row: any) => {
      return row.on_time_rate ? `${row.on_time_rate}%` : "-";
    },
  },
  {
    label: "排名",
    prop: "rank",
    minWidth: 80,
    align: "center",
  },
];

// 责任人报表列配置
const personColumns: TableColumn[] = [
  {
    label: "责任人",
    prop: "responsible_person",
    minWidth: 120,
  },
  {
    label: "所属部门",
    prop: "department_name",
    minWidth: 150,
  },
  {
    label: "负责资产数",
    prop: "asset_count",
    minWidth: 120,
    align: "right",
  },
  {
    label: "处理资产数",
    prop: "processed_count",
    minWidth: 120,
    align: "right",
  },
  {
    label: "待处理资产",
    prop: "pending_count",
    minWidth: 120,
    align: "right",
  },
  {
    label: "处理率",
    prop: "processing_rate",
    minWidth: 100,
    align: "right",
    formatter: (row: any) => {
      return row.processing_rate ? `${row.processing_rate}%` : "-";
    },
  },
  {
    label: "平均处理时间",
    prop: "avg_processing_time",
    minWidth: 120,
    align: "right",
    formatter: (row: any) => {
      return row.avg_processing_time ? `${row.avg_processing_time}天` : "-";
    },
  },
  {
    label: "准时率",
    prop: "on_time_rate",
    minWidth: 100,
    align: "right",
    formatter: (row: any) => {
      return row.on_time_rate ? `${row.on_time_rate}%` : "-";
    },
  },
  {
    label: "综合评分",
    prop: "overall_score",
    minWidth: 100,
    align: "right",
  },
  {
    label: "排名",
    prop: "rank",
    minWidth: 80,
    align: "center",
  },
];

// 根据报表类型获取列配置
const tableColumns = computed<TableColumn[]>(() => {
  switch (activeTab.value) {
    case "asset":
      return assetColumns;
    case "task":
      return taskColumns;
    case "risk":
      return riskColumns;
    case "department":
      return departmentColumns;
    case "person":
      return personColumns;
    default:
      return departmentColumns;
  }
});

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true;
  try {
    const queryParams: any = {
      report_type: activeTab.value,
      page: pagination.currentPage,
      per_page: pagination.pageSize,
      time_range: props.timeRange === "custom" ? "custom" : props.timeRange,
    };

    if (props.timeRange === "custom" && props.dateRange) {
      queryParams.start_date = formatDate(props.dateRange[0]);
      queryParams.end_date = formatDate(props.dateRange[1]);
    }

    const result = await getDetailReport(queryParams);
    
    if (result.data) {
      // 根据接口返回的数据结构调整
      tableData.value = result.data.data || result.data.details || [];
      pagination.total = result.data.pagination?.total || 0;
      pagination.currentPage = result.data.pagination?.page || 1;
      pagination.pageSize = result.data.pagination?.per_page || 10;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取报表数据失败");
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchTableData();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchTableData();
};

// 标签页切换
const handleTabChange = (tab: string) => {
  activeTab.value = tab;
  pagination.currentPage = 1;
  emit("tab-change", tab);
  fetchTableData();
};

// 监听时间范围变化
watch(
  () => [props.timeRange, props.dateRange],
  () => {
    if (activeTab.value) {
      pagination.currentPage = 1;
      fetchTableData();
    }
  },
  { deep: true }
);

// 获取风险等级标签类型
const getRiskLevelType = (level: string): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    critical: "danger",
    high: "danger",
    medium: "warning",
    low: "success",
  };
  return typeMap[level] || "info";
};

// 获取风险等级标签文本
const getRiskLevelLabel = (level: string): string => {
  const item = riskLevelList.find((item) => item.value === level);
  return item?.label || level;
};

// 获取状态标签类型
const getStatusType = (status: string): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    success: "success",
    completed: "success",
    running: "warning",
    failed: "danger",
    error: "danger",
    pending: "info",
  };
  return typeMap[status] || "info";
};

// 获取处理状态标签类型
const getProcessingStatusType = (
  status: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    processed: "success",
    confirmed: "success",
    pending: "warning",
    rejected: "danger",
    ignored: "info",
  };
  return typeMap[status] || "info";
};

// 初始化
fetchTableData();

// 暴露方法供父组件调用
defineExpose({
  refresh: fetchTableData,
  getActiveTab: () => activeTab.value,
});
</script>

<style scoped lang="scss">
.detail-report-table {
  .report-tabs {
    margin-bottom: 15px;
  }

  .table-content {
    position: relative;
  }

  .no-data {
    color: #909399;
    font-size: 12px;
  }
}
</style>

